import 'dart:convert';
import 'dart:math';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';
import 'package:qianyi/entity/home/trendVo.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/home/trend_view_model.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

import '../../../../../controller/imageDetailVideoController.dart';
import '../../../../../network/base_entity.dart';
import '../../../../../network/http_config.dart';
import '../../../../../network/http_entity.dart';
import '../../../../../ui/watefall/common/data/tu_chong_repository.dart';
import '../../../../../ui/watefall/common/widget/push_to_refresh_header.dart';
import '../../../../../ui/watefall/pages/complex/known_sized_demo.dart';
import '../../../../../ui/widget/custom_refresh.dart';

/// HACK: 社区-关注

class PageViewLike extends StatefulWidget {
  const PageViewLike({Key? key}) : super(key: key);

  @override
  State<PageViewLike> createState() => _PageViewLikeState();
}
class LikeSizedDemo1 extends StatefulWidget {
  @override
  _LikeSizedDemo1State1 createState() => _LikeSizedDemo1State1();
}
class LikeRepository extends LoadingMoreBase<TrendEntity> {
  TokenController tokenController = Get.find();

  LikeRepository({this.maxLength = 300});
  int _pageIndex = 1;
  bool _hasMore = true;
  bool forceRefresh = false;



  @override
  bool get hasMore => (_hasMore && length < maxLength) || forceRefresh;
  final int maxLength;

  Future<bool> refresh([bool notifyStateChanged = false]) async {
    _hasMore = true;
    _pageIndex = 1;
    //force to refresh list when you don't want clear list before request
    //for the case, if your list already has 20 items.
    forceRefresh = !notifyStateChanged;
    final bool result = await super.refresh(notifyStateChanged);
    forceRefresh = false;
    return result;
  }
  @override
  Future<bool> loadData([bool isloadMoreAction = false]) async {
    bool isSuccess = false;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Map<String,dynamic> userInfo = jsonDecode(prefs.getString("userInfo")!);


    Map<String, dynamic> params = {};
    params["uid"] = userInfo["id"];

    IBaseEntity? result = await HttpManager.getInstance().request(url: "/platform/follow/getAllFollowTrends/${_pageIndex}/10",method: Method.get, params: params);
    HttpEntity httpEntity = result as HttpEntity;
    TrendEntityList trendEntityList = TrendEntityList.fromJson(httpEntity.oriData);
    List<String> imageIds = trendEntityList.getImageIds();
    Map<String,dynamic> params1 = {
      "imageIds": imageIds
    };

    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: "/platform/imgDetail/getCovers",method: Method.post,params: params1) as HttpEntity;
    List<String> returnImages = httpEntity1.getOriData()['data'].cast<String>();
    List<String> reversedImages = returnImages.reversed.toList();

    for (var i = 0; i < trendEntityList.trends!.length; i++) {
      trendEntityList.trends![i].cover = reversedImages[i];
    };

    _pageIndex++;

    isSuccess = true;
    return isSuccess;
  }

}

class _LikeSizedDemo1State1 extends State<LikeSizedDemo1> {
  LikeRepository listSourceRepository = LikeRepository();
  TokenController tokenController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();

  DateTime? dateTimeNow;
  @override
  void dispose() {
    super.dispose();
    listSourceRepository.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PullToRefreshNotification(
      pullBackOnRefresh: false,
      maxDragOffset: maxDragOffset,
      armedDragUpCancel: false,
      onRefresh: onRefresh,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PullToRefreshContainer(
                    (PullToRefreshScrollNotificationInfo? info) {
                  return PullToRefreshHeader(info, dateTimeNow);
                }),
          ),
          LoadingMoreSliverList<TrendEntity>(
            SliverListConfig<TrendEntity>(
              extendedListDelegate:
              const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300,
                crossAxisSpacing: 5,
                mainAxisSpacing: 5,
              ),
              itemBuilder: buildWaterfallFlowItem1,
              sourceList: listSourceRepository,
              padding: const EdgeInsets.all(5.0),
              lastChildLayoutType: LastChildLayoutType.foot,
            ),
          )
        ],
      ),
    );
  }
  Map<int, double> imagesHeightMap = {};

  double getRandomHeight1(int index) {
    // 检查imagesHeightMap中是否已经存在对应索引的高度
    if (imagesHeightMap.containsKey(index)) {
      // 如果存在，返回该高度
      return imagesHeightMap[index]!;
    } else {
      // 如果不存在，生成一个新的随机高度并添加到Map中
      double height = Random().nextDouble() * (200 - 80) + 168;
      imagesHeightMap[index] = height;
      return height;
    }
  }
  Widget buildWaterfallFlowItem1(BuildContext c, TrendEntity item, int index,
      {bool konwSized = true}) {
    const double fontSize = 12.0;

    TrendEntity trendEntity = item;

    return GestureDetector(
      onTap: () async {
        HudUtil.showBeautiful(context);
        Map<String,dynamic> params = {
          "uid":tokenController.uid,
          "mid":trendEntity.mid!
        };
        HttpManager.getInstance().request(url: "/platform/browseRecord/addBrowseRecord",params: params,method: Method.post);

        imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
        await imageDetailVideoController.getImageVideoDetail();
        // Loader.hide();
        HudUtil.dismiss();
        Get.toNamed("/ui/home/imageVideoDetail");

      },
      child: Card(
        margin: EdgeInsets.all(1.5),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.0),
          child:  Column(
            children: [
              FancyShimmerImage(

                height: getRandomHeight1(index),
                imageUrl: trendEntity.cover!,
              )
              ,


              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                  overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                ),

              )
              ,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                          child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                      ),

                      Text(trendEntity.username as String),
                    ],
                  ),

                  Row(
                    children: [
                      Icon(
                        CupertinoIcons.heart,size: 14,),
                      Text(trendEntity.agreeCount as String)

                    ],
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
  Future<bool> onRefresh() {
    return listSourceRepository.refresh().whenComplete(() {
      dateTimeNow = DateTime.now();
    });
  }
}


class _PageViewLikeState extends State<PageViewLike> with AutomaticKeepAliveClientMixin,TickerProviderStateMixin{
  List<MockLike> items = [];
  TokenController tokenController = Get.find();
  TextDirection textDirection = TextDirection.ltr;
  int crossAxisCount = 2;
  double crossAxisSpacing = 5.0;
  double mainAxisSpacing = 5.0;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {

  }

  void _onLoading() async {

  }

  @override
  void initState() {
    super.initState();

    setState(() {
      items = MockLike.get();
    });
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(

      body: KnownSizedDemo1()



    )
      ;

  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  Map<int, double> imagesHeightMap = {};

  double getRandomHeight(int index) {
    // 检查imagesHeightMap中是否已经存在对应索引的高度
    if (imagesHeightMap.containsKey(index)) {
      // 如果存在，返回该高度
      return imagesHeightMap[index]!;
    } else {
      // 如果不存在，生成一个新的随机高度并添加到Map中
      double height = Random().nextDouble() * (200 - 80) + 168;
      imagesHeightMap[index] = height;
      return height;
    }
  }
  buildWateFall(TrendViewModel viewModel) {
    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    List<double> lists = getAllHeight(viewModel.datas.length);
    return
      MasonryGridView.count(
        addAutomaticKeepAlives: true,
      padding: EdgeInsets.all(0),
      // 展示几列
      crossAxisCount: 2,
      // 元素总个数
      itemCount: viewModel.datas.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) {
        TrendEntity trendEntity = viewModel.datas[index];
        // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
        return
          GestureDetector(
          onTap: () async {

           HudUtil.showBeautiful(context);


            String uid = await tokenController.getUid();
            Map<String,dynamic> params = {
              "mid":trendEntity.mid,
              "uid": uid
            };
            await HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
            imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
            await imageDetailVideoController.getImageVideoDetail();

            // Loader.hide();
            HudUtil.dismiss();

            Get.toNamed("/ui/home/imageVideoDetail");
          },
          child: Card(
             // 确保Card有颜色
              margin: EdgeInsets.all(1.5),
              elevation: 1.0, // 卡片阴影
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4.0),
                child:  Column(
                  children: [
                    FancyShimmerImage(
                      height: getRandomHeight(index),
                      imageUrl: trendEntity.cover!,
                    ),

                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center, // 确保所有的子组件从顶部开始排列
                      children: [

                        trendEntity.imgsUrl!.toLowerCase().contains('.mp4')
                            ? Icon(Icons.video_collection_outlined, color: WcaoTheme.placeholder.withOpacity(.8))
                            : Icon(Icons.image_outlined, color: WcaoTheme.placeholder.withOpacity(.8)),
                        SizedBox(width: 8),
                        Flexible(
                          child: Text(
                            '${trendEntity.content as String}',
                            maxLines: 2,
                            softWrap: true,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontWeight: FontWeight.w400),
                          ),
                        ),
                        // 使用SizedBox来添加一些空间，这样图标不会紧贴着文字

                      ],
                    )

                    ,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            ClipOval(
                                child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                            ),

                            Text(trendEntity.username as String),
                          ],
                        ),

                        Row(
                          children: [
                            Icon(trendEntity.isAgree!?
                            CupertinoIcons.heart_fill: CupertinoIcons.heart,size: 14,
                              color: trendEntity!.isAgree!?Colors.red:Colors.grey,),
                            Text(trendEntity.agreeCount as String)

                          ],
                        )
                      ],
                    )
                  ],
                ),
              ),
            )

          ,
        )
        ;
      },

      // 纵向元素间距
      mainAxisSpacing: 0,
      // 横向元素间距
      crossAxisSpacing: 0,
      //本身不滚动，让外面的singlescrollview来滚动
      physics:const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    )


    ;


  }
  List<Color> colors = <Color>[];

  Color getRandomColor(int index) {
    if (index >= colors.length) {
      colors.add(Color.fromARGB(255, Random.secure().nextInt(255),
          Random.secure().nextInt(255), Random.secure().nextInt(255)));
    }

    return colors[index];
  }

   getAllHeight(int length) {
    List<double> heights = [];
    for(int i = 0; i < length; i++) {
      heights.add(getRandomHeight(i)) ;
    }
    return heights;
  }
}
